package interviewClassic150;

import org.junit.Test;

public class StrStr {
    public int strStr(String haystack, String needle) {
        //KMP算法
        //创建next数组
        int[] next = constructNext(needle);
        for (int i = 0,j = 0; i < haystack.length(); i++) {
            while (j > 0 && haystack.charAt(i) != needle.charAt(j)) j = next[j - 1];
            if (haystack.charAt(i) == needle.charAt(j)) j++;
            if (j == needle.length()) return i - j + 1;
        }
        //到最后都没匹配成
        return -1;
    }

    private int[] constructNext(String s) {
        int[] next = new int[s.length()];
        next[0] = 0;
        for (int i = 1, j = 0; i < s.length(); i++) {
            while (j > 0 && s.charAt(i) != s.charAt(j)) j = next[j - 1];
            if (s.charAt(i) == s.charAt(j)) j++;
            next[i] = j;
        }
        return next;
    }

    @Test
    public void test() {
        String hayStack = "abeababeabf";
        String needle = "aaabbab";

        int index = strStr(hayStack,needle);
        System.out.println(index);
    }
}
